package com.jianhua.backend.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jianhua.backend.domain.dto.UserDto;
import com.jianhua.backend.domain.entity.Orders;
import com.jianhua.backend.domain.entity.User;
import com.jianhua.backend.domain.vo.PageVo;
import com.jianhua.backend.mapper.UserMapper;
import com.jianhua.backend.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 存储系统所有用户的基本信息，包括客户、后厨人员和管理员 服务实现类
 * </p>
 *
 * @author author
 * @since 2025-07-02
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public PageVo<User> listUser(UserDto userDto) {
        Page<User> page = new Page<>(userDto.getPage(), userDto.getSize());
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        if (userDto.getNickname() != null) {
            queryWrapper.like(User::getNickname, userDto.getNickname());
        }
        if (userDto.getPhone() != null) {
            queryWrapper.like(User::getPhone, userDto.getPhone());
        }
        Page<User> userPage = userMapper.selectPage(page, queryWrapper);
        long total = page.getTotal();
        Integer count = Integer.valueOf((int) total);
        List<User> records = userPage.getRecords();
        return new PageVo<>(count, records);
    }

    @Override
    public User getUserById(Integer id) {
        return userMapper.selectById(id);
    }

    @Override
    public void updateUser(User user) {
        int i = userMapper.updateById(user);
        if(i < 0){
            //todo: 抛出修改失败异常
        }
    }

    @Override
    public void deleteUser(Integer id) {
        int i = userMapper.deleteById(id);
        if(i < 0){
            //todo: 抛出删除失败异常
        }
    }

    @Override
    public void register(User newUser) {
        this.save(newUser); 
    }

    @Override
    public User findByUserName(String username) {
        return this.getOne(new LambdaQueryWrapper<User>().eq(User::getUsername, username));
    }

    @Override
    public void updatePassword(Integer userId, String newPassword) {
        LambdaUpdateWrapper<User> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(User::getUserId, userId)
                .set(User::getPassword, newPassword);
        userMapper.update(null, updateWrapper);
    }
}
